<?php

namespace Admin\Controller;

use Think\Controller;

class LinkController extends CommonController
{
    public function ajaxLink()//lst 链接管理 查询所有链接
    {

        $model_link_manage = D('link');
        $l = I('get.limit');
        $l = !$l ? 6 : $l;

        $p = I('get.page');
        $p = $p <= 0 ? 1 : $p;

        $p = ($p - 1) * $l; //(页码 - 1 ) * 单页条数

        $res = $model_link_manage->query("SELECT * FROM link LIMIT $p,$l");// 从第$p条开始 取$n条

        $count = $model_link_manage->query("SELECT count(1)  AS num FROM link ");

        $code = !$res ? self::RET_FAILED : self::RET_SUCCESS;
        $msg = !$res ? '暂无信息' : '提示信息';
//        $this->ajaxReturn(array('data' => $res, 'count' => $count[0]['num'], 'code' => empty($res) ? 1 : 0, 'msg' => empty($res) ? '暂无信息' : '提示信息'));
        $this->ajaxRet($code,$msg,$res,$count[0]['num']);
    }

    public function add()//添加友情链接
    {
        $model_link = D('Link');
//        $post=$_POST;
        if (IS_POST) {
            $data['title'] = I('post.title');
            $data['url'] = I('post.url');
            $data['desc'] = I('post.desc');
            if ($model_link->create($data)) {
                if ($model_link->add()) {
                    $this->success('添加友情链接成功！', U('lst'));
                } else {
                    $this->arror('添加友情链接失败！');
                }
            } else {
                $this->error($model_link->getError());
            }
            return;
        }
        $this->display();
    }

    public function del()//删除链接
    {
        $data = $_POST;
        $model_del = M("link"); // 实例化User对象
        $model_del->where("id=$data[id]")->delete(); // 删除id为5的用户数据
        $count = $model_del->query("SELECT count(1)  AS num FROM link ");
        $this->ajaxReturn(array('data' => $model_del, 'count' => $count[0]['num']));
        $this->ajaxRet(self::RET_SUCCESS, '删除成功', $model_del, $count[0]['num']);


    }

    public function up()//修改链接
    {
        $data = $_POST;
        $model_up = M("link"); // 实例化User对象
        $count = $model_up->query("SELECT count(1)  AS num FROM link ");
        $model_up->where("id=$data[id]")->save($data); // 根据条件更新记录
        $this->ajaxRet(self::RET_SUCCESS, '修改成功', $model_up, $count[0]['num']);


    }

    public function checkTitle()//验证链接名是否存在
    {
        $title = $_POST['title'];
        $model_link = D('link');
        $sql = sprintf("SELECT * FROM link WHERE title = '%s'", $title);
        $res = $model_link->query($sql);
        $code = !$res ? self::RET_FAILED : self::RET_SUCCESS;
        $msg = !$res ? '可用' : '不可用';
        $this->ajaxRet($code, $msg);
    }
}